<template>  
  <div class="inventory-management">  
     
    <div class="toolbar">  
        <!-- 查询参数 -->  
        <input type="text" v-model="searchName" placeholder="产品名称：" />  
        <select v-model="warehouseId">  
            <option value="请选择">请选择</option>  
            <option value="1号仓库">1号仓库</option>  
            <option value="2号仓库">2号仓库</option>  
            <option value="3号仓库">3号仓库</option>  
        </select>  
        <button @click="fetchInventoryData">重置</button>     
        <!-- 其他按钮 -->  
       
         <button @click="refreshData">刷新</button>  
 
        <button @click="exportData">导出</button>
      
       
    </div> 

  <table> 
      <thead>  
        <tr>            
          <th>产品名称</th>  
          <th>产品规格</th>  
          <th>仓库</th>             
          <th>下限</th> 
           <th>上限</th> 
          <th>库存数</th>  
        </tr>  
      </thead>  
      <tbody>  
        <tr v-for="item in inventoryItems" :key="item.id"> 
          
          <td>{{ item.productName }}</td>  
          <td>{{ item.specification }}</td>  
          <td>{{ item.defaultRepository }}</td>
             
          <td>{{ item.earlyWarningFront }}</td>  
           <td>{{ item.earlyWarningBelow }}</td>
          
         <td :class="{'green': item.sumStock <= item.earlyWarningBelow && item.sumStock >= item.earlyWarningFront, 'red': (item.sumStock > item.earlyWarningBelow || item.sumStock < item.earlyWarningFront)}">{{ item.sumStock }}</td> 
        </tr>  
      </tbody>  
    </table>  
      <!-- 分页控件（示例） -->
  
  </div>  
  <footer>  
    <div class="pagination">  
              <el-pagination
  :page-size="pageSize"
  :current-page="currentPage"
  :total="totalItems"
  @current-change="handleCurrentChange"
>
</el-pagination>
    </div>  
  </footer>  
</template>

<script>
import * as XLSX from 'xlsx';  
import { saveAs } from 'file-saver';
export default {  
  name: 'InventoryManagement',  
   data() {  
    return {  
        inventoryItems: [],  
        totalItems: 0,  
        currentPage: 1,  
        pageSize: 10,  
         totalPages: 0, // 新增总页数  
        searchName: '',  
        warehouseId: '请选择',  
    };  
    },

 mounted() {  
    this.fetchInventoryData();  
    }, 
methods: {  
  async  fetchInventoryData() {  
        this.http.get(`base-read/api/product/getstockwaring?name=${this.searchName}&wareHouseId=${this.warehouseId}&page=${this.currentPage}&size=${this.pageSize}`)  
            .then(response => {  
                this.inventoryItems = response.items;  
                this.totalItems = response.total;  
                 this.totalPages = Math.ceil(this.totalItems / this.pageSize); // 更新总页数  
          // 确保当前页在有效范围内  
          if (this.currentPage > this.totalPages) {  
            this.currentPage = this.totalPages;  
          }  
            })  
            .catch(error => {  
                console.error(error);  
            });  
    },  
     exportData() {  
         // 准备表格数据  
     const headers = ["产品编号", "产品名称", "规格", "仓库", "上限", "下限", "库存数"]; // 表头
      const ws_data = this.inventoryItems.map(item => [  
        item.id,  
        item.productName,  
        item.specification,  
        item.defaultRepository,  
        item.earlyWarningFront,  
        item.earlyWarningBelow,  
        item.sumStock  
      ]);  
      // 将表头添加到ws_data数组的最前面  
    const finalData = [headers, ...ws_data];
      // 添加表头  
      const ws_name = "库存预警";  
      const wb = XLSX.utils.book_new();  
      const ws = XLSX.utils.aoa_to_sheet(finalData);  
      XLSX.utils.book_append_sheet(wb, ws, ws_name);  
  
      // 导出工作簿  
      XLSX.writeFile(wb, `${ws_name}.xlsx`);  
  
      // 或者使用file-saver来更优雅地处理下载  
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });  
      const blob = new Blob([this.s2ab(wbout)], { type: 'application/octet-stream' });  
      saveAs(blob, `${ws_name}.xlsx`);  
    },  
    // 字符串转ArrayBuffer  
    s2ab(s) {  
      const buf = new ArrayBuffer(s.length);  
      const view = new Uint8Array(buf);  
      for (let i = 0; i < s.length; i++) {  
        view[i] = s.charCodeAt(i) & 0xFF;  
      }  
      return buf;  
    },  
     refreshData() {  
            // 重置查询条件  
            this.searchName = '';  
            this.warehouseId = '请选择';  
            // 重置当前页码（可选，根据需要）  
            this.currentPage = 1;  
            // 重新加载数据  
            this.fetchInventoryData();  
        },  
 
  async  handleCurrentChange(newPage) {  
      // 确保新页码在有效范围内  
      const newPageValue = Math.min(Math.max(1, newPage), this.totalPages);  
      if (newPageValue !== this.currentPage) {  
        this.currentPage = newPageValue;  
        this.fetchInventoryData();  
      }  
    },  
  
}, 
};  
</script>  
  
<style scoped>  
.inventory-management {  
  font-family: Arial, sans-serif;  
  color: #333;  
}  
  
.toolbar {  
  display: flex;  
  justify-content: space-between;  
  align-items: center;  
  padding: 10px;  
  background-color: #f0f0f0;  
}  
  
.toolbar button {  
  margin-right: 10px;  
}  
  
table {  
  width: 100%;  
  border-collapse: collapse;  
  margin-top: 20px;  
}  
  
th, td {  
  border: 1px solid #ddd;  
  padding: 8px;  
  text-align: left;  
}  
  
th {  
  background-color: #007bff;  
  color: white;  
}  
  
tr:nth-child(even) {  
  background-color: #f2f2f2;  
}  
.green {  
  color: green;  
}  
.red {  
  color: red;  
}
</style>